# -*- coding: cp949 -*-
from xmlbook import *
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, HTTPServer
import xml.dom.minidom

##global
conn = None
regKey = '5432211430547460eb22062cde0b1a74'

server = "openapi.naver.com"

host = "smtp.gmail.com" 
port = "587"

def userURIBuilder(server,**user):
    str = "http://" + server + "/search" + "?"
    for key in user.keys():
        str += key + "=" + user[key] + "&"
    return str

def connectOpenAPIServer():
    global conn, server
    conn = HTTPConnection(server)
        
def getMovieDataFromDirector(director):
    global server, regKey, conn
    if conn == None :
        connectOpenAPIServer()
    uri = userURIBuilder(server, key=regKey, query='%20', display="1", start="1", target="movie", director=director)
    conn.request("GET", uri)
    
    req = conn.getresponse()
    print('\n')
    if int(req.status) == 200 :
        data = req.read()
        dom = xml.dom.minidom.parseString(data)
        return extractMovieData(dom.toxml())
    else:
        print ("OpenAPI request has been failed!! please retry")
        return None

def getMovieDataFromKeyword(keyword):
    global server, regKey, conn
    if conn == None :
        connectOpenAPIServer()
    uri = userURIBuilder(server, key=regKey, query=keyword, display="10", start="1", target="movie")
    conn.request("GET", uri)
    
    req = conn.getresponse()

    print('\n')
    if int(req.status) == 200 :
        data = req.read()
        dom = xml.dom.minidom.parseString(data)

        return extractMovieData(dom.toxml())
    else:
        print ("OpenAPI request has been failed!! please retry")
        return None

def extractMovieData(strXml):
    import xml.etree.ElementTree as ET
    root = ET.fromstring(strXml)

    for element in root.iter("item"):
       strTitle = element.find("title").text
       directorName = element.find("director").text
       userRate = element.find("userRating").text
       print("Title: ", strTitle, "Director: ", directorName, "UserRating: ", userRate)
       
